import React, {useEffect, useState, useRef, useLayoutEffect} from 'react';
import {
    SafeAreaView,
    View,
    Dimensions,
    useWindowDimensions,
    ScrollView,
    Text,
    StyleSheet
} from 'react-native';
import {connect} from "react-redux";
import {ShareView} from '../../components';
import {defaultNavigationConfigure} from "../../base/navconfig";
import Icon from "react-native-vector-icons/AntDesign";
import {useNavigation, useRoute} from "@react-navigation/native";
import StatusBarCtl from "../../utils/StatusBarCtl";
import ApiService from "../../utils/ApiService";
import RenderHTML from "react-native-render-html";
import moment from "moment";
import PostListItem from "./components/PostListItem";
import {LoadingView} from "react-native-gzdsx-elements";

const RelatedView = (props) => {
    const navigation = useNavigation();
    const [dataList, setDataList] = useState([]);

    const {post = {}} = props;
    useEffect(() => {
        let params = {limit: 5, sort: 'time-desc'}
        if (post && post.categories) {
            params.cate = post.categories.map(c => c.cate_id).join(',');
        }
        ApiService.get('/posts', {params}).then(response => {
            setDataList(response.result.items);
        });
    }, []);


    return (
        <View style={{marginTop: 10}}>
            <View style={{paddingHorizontal: 15}}>
                <Text style={{fontSize: 22, fontWeight: '600'}}>相关阅读</Text>
            </View>
            {
                dataList.map((item, index) => (
                    <PostListItem item={item} key={index.toString()} onPress={() => {
                        navigation.push('PostDetail', {id: item.id});
                    }}/>
                ))
            }
        </View>
    )
}

const renderersProps = {
    img: {
        enableExperimentalPercentWidth: true
    }
};

const PostDetail = (props) => {

    const route = useRoute();
    const navigation = useNavigation();
    const [post, setPost] = useState({});
    const [content, setContent] = useState({});
    const [shareMessage, setShareMessage] = useState({});
    const [loading, setLoading] = useState(true);
    const [showShare, setShowShare] = useState(false);
    const [subscribed, setSubscribed] = useState(false);

    const shareRef = useRef(null);
    const {width} = useWindowDimensions();

    useLayoutEffect(() => {
        fetchData();
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            title: '',
        });
        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, [navigation]);

    const setNavigation = () => {
        navigation.setOptions({
            headerRight: () => (
                <View style={{flexDirection: 'row', columnGap: 10}}>
                    <Icon
                        name={subscribed ? 'star' : 'staro'}
                        size={25}
                        color={"#333"}
                        suppressHighlighting={true}
                        onPress={addSubscribe}
                    />
                    <Icon
                        name={'sharealt'}
                        size={25}
                        color={"#333"}
                        suppressHighlighting={true}
                        onPress={() => {
                            shareRef.current.show();
                        }}
                    />
                </View>
            )
        });
    }

    const fetchData = () => {
        const id = route.params?.id;
        ApiService.get('/posts/' + id).then(response => {
            //console.log(response);
            const {title, image, excerpt, content} = response.result;
            setPost(response.result);
            if (content) setContent(content);
            setShareMessage({
                type: 'news',
                title: title,
                description: excerpt,
                thumbImage: image || '',
                webpageUrl: 'https://shop.gzdsx.cn/apps'
            });
            setNavigation();
        }).catch(reason => {
            console.log(reason);
        }).finally(() => {
            setLoading(false);
        });
    }

    const addSubscribe = () => {

    }

    if (loading) {
        return <LoadingView/>;
    }

    return (
        <SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
            <ScrollView style={{flex: 1}}>
                <View style={styles.header}>
                    <View style={styles.title}>
                        <Text style={styles.titleText}>{post.title}</Text>
                    </View>
                    <View style={styles.meta}>
                        <Text style={styles.siteName}>大师兄微小店客户端</Text>
                        <Text style={styles.pubTime}>{moment(post.created_at).format('yyyy年MM月DD日 HH:mm')}</Text>
                    </View>
                </View>
                <View style={styles.body}>
                    <RenderHTML
                        source={{html: content.content}}
                        contentWidth={Dimensions.get('window').width - 30}
                        renderersProps={renderersProps}
                        baseStyle={{
                            fontSize: 18,
                            fontWeight: '350',
                            color: '#333',
                            lineHeight: 28
                        }}
                        emSize={0}
                        enableExperimentalMarginCollapsing={true}
                        ignoredDomTags={['a', 'div']}
                    />
                </View>
                <RelatedView post={post}/>
            </ScrollView>
            <ShareView show={showShare} ref={shareRef}/>
        </SafeAreaView>
    );
}

const mapStateToProps = state => {
    return state;
};

export default connect(mapStateToProps)(PostDetail);

const styles = StyleSheet.create({
    header: {
        paddingVertical: 10,
        paddingHorizontal: 15
    },
    body: {
        paddingHorizontal: 15,
        textAlign: 'justify'
    },
    title: {
        paddingVertical: 10,
        marginBottom: 10
    },
    titleText: {
        fontSize: 24,
        color: '#333',
        fontWeight: '600'
    },
    meta: {
        marginBottom: 0
    },
    siteName: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 6
    },
    pubTime: {
        fontSize: 12,
        color: '#838383'
    }
})
